import { getMenu, getPermissionInfo, login } from '@/services/auth';
import { LockOutlined, UserOutlined } from '@ant-design/icons';
import { LoginForm, ProFormText } from '@ant-design/pro-components';
import { useEmotionCss } from '@ant-design/use-emotion-css';
import { FormattedMessage, history, SelectLang, useIntl, Helmet, useModel } from '@umijs/max';
import { Alert, message, theme } from 'antd';
import Settings from '../../../../config/defaultSettings';
import React, { useEffect, useState } from 'react';
import { flushSync } from 'react-dom';
import { setToken } from '@/utils/tokenManegerUtils';
import { checkRespSuccessful } from '@/utils/serviceUtils';
import { REDIRECT_KEY, RespStatusCode } from '@/constants';
import { getDictSelectList } from '@/services/system/dict';
import { dictListToGroup } from '@/utils/dictUtils';
import { menuFormat } from '@/utils/menuUtils';

const Lang = () => {
  const langClassName = useEmotionCss(({ token }) => {
    return {
      width: 42,
      height: 42,
      lineHeight: '42px',
      position: 'fixed',
      right: 16,
      borderRadius: token.borderRadius,
      ':hover': {
        backgroundColor: token.colorBgTextHover,
      },
    };
  });

  return (
    <div className={langClassName} data-lang>
      {SelectLang && <SelectLang />}
    </div>
  );
};

const LoginMessage: React.FC<{
  content: string;
}> = ({ content }) => {
  return (
    <Alert
      style={{
        marginBottom: 24,
      }}
      message={content}
      type="error"
      showIcon
    />
  );
};

const Login: React.FC = () => {
  const { initialState, setInitialState } = useModel('@@initialState');
  const [userLoginState, setUserLoginState] = useState<string>('');
  const { useToken } = theme;
  const { token } = useToken();
  // 初始化
  useEffect(() => {
    setInitialState({
      ...initialState,
      currentUser: undefined,
    });
  }, []);

  const intl = useIntl();

  const handleSubmit = async (values: API.LoginParams) => {
    try {
      if (!values.username || !values.password) {
        const tipMsg = intl.formatMessage({
          defaultMessage: '请输入用户名及密码',
        });
        message.error(tipMsg);
        return;
      }
      // 登录
      const res = await login(values.username, values.password);
      if (checkRespSuccessful(res) && res.data && res.data.accessToken && res.data.refreshToken) {
        const { accessToken, refreshToken } = res.data;
        setToken({
          accessToken,
          refreshToken,
        });
        const getUserInfoRes = await getPermissionInfo();
        const getDictSelectListRes = await getDictSelectList();
        let menuTree: System.MenuTreeNode[] = [];
        const getMenuRes = await getMenu();
        if (checkRespSuccessful(getMenuRes) && getMenuRes.data) {
          menuTree = menuFormat(getMenuRes.data);
        }
        if (checkRespSuccessful(getUserInfoRes) && checkRespSuccessful(getDictSelectListRes)) {
          flushSync(() => {
            setInitialState((initialState) => ({
              ...initialState,
              currentUser: getUserInfoRes.data,
              menuTree,
              ...dictListToGroup(getDictSelectListRes.data || []),
            }));
          });
          const tipMsg = intl.formatMessage({
            id: 'pages.login.success',
            defaultMessage: '登录成功',
          });
          message.success(tipMsg);
          const urlParams = new URL(window.location.href).searchParams;
          history.push(urlParams.get(REDIRECT_KEY) || '/');
          return;
        }
      }
      if (res.code === RespStatusCode.BAD_PASSWORKD) {
        // 如果失败去设置用户错误信息
        setUserLoginState('badPassword');
      } else {
        message.error(`登录失败，后台响应：${res.message}`);
      }
    } catch (error) {
      const defaultLoginFailureMessage = intl.formatMessage({
        id: 'pages.login.failure',
        defaultMessage: '登录失败，请重试',
      });
      console.error(error);
      message.error(defaultLoginFailureMessage);
    }
  };

  return (
    <div
      style={{
        width: '100vw',
        height: '100vh',
        boxSizing: 'border-box',
        padding: token.padding,
        backgroundColor: '#39a4e1',
      }}
    >
      <embed
        id="svg"
        type="image/svg+xml"
        style={{
          position: 'fixed',
          bottom: 0,
          left: 0,
          zIndex: 0,
        }}
        src="/svg/wave-bg.svg"
      />
      <Helmet>
        <title>
          {intl.formatMessage({
            id: 'menu.login',
            defaultMessage: '登录页',
          })}
          - {Settings.title}
        </title>
      </Helmet>
      <Lang />
      <div
        style={{
          margin: '0 auto',
          borderRadius: token.borderRadiusLG,
          boxShadow: token.boxShadow,
          width: 500,
          marginTop: '10%',
          backgroundColor: 'rgba(255, 255, 255, 0.6)',
          overflow: 'hidden',
          position: 'relative',
          zIndex: 1,
        }}
      >
        <LoginForm
          logo={<img alt="logo" src="/assets/logo.png" />}
          title="自助设备统一管理平台"
          subTitle="精心设计的自助设备统一管理平台"
          onFinish={async (values) => {
            await handleSubmit(values as API.LoginParams);
          }}
          onFocus={() => {
            setUserLoginState('');
          }}
        >
          {userLoginState === 'badPassword' && (
            <LoginMessage
              content={intl.formatMessage({
                id: 'pages.login.accountLogin.errorMessage',
                defaultMessage: '账户或密码错误',
              })}
            />
          )}
          <ProFormText
            name="username"
            fieldProps={{
              size: 'large',
              prefix: <UserOutlined />,
            }}
            placeholder={intl.formatMessage({
              id: 'pages.login.username.placeholder',
              defaultMessage: '用户名',
            })}
            rules={[
              {
                required: true,
                message: (
                  <FormattedMessage
                    id="pages.login.username.required"
                    defaultMessage="请输入用户名"
                  />
                ),
              },
            ]}
          />
          <ProFormText.Password
            name="password"
            fieldProps={{
              size: 'large',
              prefix: <LockOutlined />,
            }}
            placeholder={intl.formatMessage({
              id: 'pages.login.password.placeholder',
              defaultMessage: '密码',
            })}
            rules={[
              {
                required: true,
                message: (
                  <FormattedMessage
                    id="pages.login.password.required"
                    defaultMessage="请输入密码"
                  />
                ),
              },
            ]}
          />
        </LoginForm>
      </div>
    </div>
  );
};

export default Login;
